var request = require('request');
var iconv = require('iconv-lite');
var BufferHelper = require('bufferhelper');
var CityToLines = require('../routes/busModels/CityToLines');
var LineToStops = require('../routes/busModels/LineToStops');

function download(url,callback){
    var req = request(url, {timeout: 10000, pool: false});
    req.on('error', function(err) {
        callback(null);
    });
    req.on('response', function(res) {
        var bufferHelper = new BufferHelper();
        res.on('data', function (chunk) {
            bufferHelper.concat(chunk);
        });
        res.on('end',function(){
            var result = iconv.decode(bufferHelper.toBuffer(),'GBK');
            callback(result);
        });
    });
}
function getBusData(url,cityName){
 return new Promise(function (resolve, reject) {
  download(url, function(data){
    if(data){
     
      var env = require('jsdom').env
      , html = data;

    // first argument can be html string, filename, or url
    env(html, async function (errors, window) {
      var $ = require('jquery')(window) ;
      var children = $('.txt').children();
      var array = [];
      for(var i =0 ; i < children.length;i++){
        var str = children[i].getAttribute('href');
        if(!str)continue;
        if(children[i].getAttribute('class')&&children[i].getAttribute('class').indexOf('f24')!=-1){
          console.log('------------');
        }
        if(str.indexOf('/i.php/') == -1)continue;
        
        array.push({
          href:'http://www.dengche.cn' + str,
          value:children[i].innerHTML
        });
        await line('http://www.dengche.cn' + str,cityName,children[i].innerHTML);
        console.log(i);
      }

      var cityToLines =  new CityToLines({
          city:cityName,
          lines:array
        });
      cityToLines.save(function(err,result){
            if(err){
              console.log(cityName);
            }else{
              // console.log(result);
            }
      });
      console.log('end');
      resolve();
      
    });
    }
  });
});
}
var lineList = [];
var line = function (url,city,line) {
  return new Promise(function (resolve, reject) {
     download(url,function(data){
    if(data){
      var env = require('jsdom').env
      , html = data;

      // first argument can be html string, filename, or url
      env(html, function (errors, window) {
        var $ = require('jquery')(window) ;
        var children = $('.txt').children();
        var up = [];
        var down = [] ;
        var cnt = 0 ;
        var temp = up;
        for(var i =0 ; i < children.length;i++){
          if(children[i].getAttribute('class')&&children[i].getAttribute('class').indexOf('fxh')!=-1)cnt++;
          if(cnt >= 2){
            temp = down;
          }
          var str = children[i].getAttribute('href');
          if(!str)continue;
          if(str.indexOf('php') == -1)continue;
          temp.push(
            children[i].innerHTML
          );

        }
        lineList.push({
          
        })
        
        var lineToStops =  new LineToStops({
            city  : city,
            line  : line+'上行',
            stops : up,
          });

        lineToStops.save(function(err,result){
              if(err){
                console.log('save line err :' + line+'up');
                resolve();
              }else{
               var lineToStops =  new LineToStops({
                    city  : city,
                    line  : line+'下行',
                    stops : down,
                 });
                lineToStops.save(function(err,result){
                      if(err){
                        console.log('save line err :' + line+'down');
                        resolve();
                      }else{
                        resolve();
                      }
                });
              }
        });
        
      });
    }else {
      console.log('get line err:'+line);
    }
    
  })
  })
};
module.exports = getBusData
